import React, { useState, useEffect } from 'react';
import { getTables, deleteTable,syncMetadata,generateCodeForIds } from '../../api/table/apiFunctions';
import { useNavigate } from 'react-router-dom';
import {
  Button,
  TextField,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Typography,
  CircularProgress,

  TablePagination,
  Snackbar,
} from '@mui/material';
import Checkbox from '@mui/material/Checkbox';

import { Form, Input } from 'antd';

import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';

const TableList = () => {
  const navigate = useNavigate();
  const [tables, setTables] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]); // 记录选中的行
  const [dialogOpen, setDialogOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20); // 每页显示条数
  const [total, setTotal] = useState(0); // 总条数
  const [editedItem, setEditedItem] = useState({});
  const [editedIndex, setEditedIndex] = useState(-1);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [queryParams, setQueryParams] = useState({
    tableName: '',
    schemaName: '',
  });

  const handleQueryParamChange = (key, value) => {
    const newQueryParams = { ...queryParams, [key]: value };
    setQueryParams(newQueryParams);
    localStorage.setItem('queryParams', JSON.stringify(newQueryParams));
  };

  useEffect(() => {
    const savedQueryParams = localStorage.getItem('queryParams');
    const parsedQueryParams = savedQueryParams ? JSON.parse(savedQueryParams) : null;

    if (parsedQueryParams) {
      setQueryParams(parsedQueryParams);
    }
    fetchTables(page, pageSize);
  }, []);

  const fetchTables = async (currentPage, currentPageSize) => {
    setLoading(true);
    try {
      const savedQueryParams = localStorage.getItem('queryParams');
      const queryParams = savedQueryParams ? JSON.parse(savedQueryParams) : null;
      const response = await getTables(currentPage - 1, currentPageSize, queryParams);
      setTables(response.data.content);
      setTotal(response.data.totalElements); // 设置总条数
    } catch (error) {
      console.error('Error fetching tables:', error);
    }
    setLoading(false);
  };

  const handleSearch = () => {
    fetchTables(page, pageSize);
  };

  const handleSyncMetadata =async () => {
     setLoading(true);
    try {
      const response = await syncMetadata();
      response.data
    } catch (error) {
      console.error('Error saving user:', error);
    }
     setLoading(false);
  };


  const handleReadColumns = (tableId,tableName) => {
    navigate(`/columns/${tableId}/${tableName}`);
  };
 

  const handleOpenEditDialog = (item) => {
    setEditedItem({ ...item });
    setEditedIndex(tables.indexOf(item));
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
  };

  const handleSaveUser = async () => {
    setLoading(true);
    try {
      await fetchTables(page, pageSize);
    } catch (error) {
      console.error('Error saving user:', error);
    }
    setDialogOpen(false);
    setLoading(false);
  };

  const handleConfirmDeletion = async (id) => {
    if (window.confirm('确定删除此用户？')) {
      setLoading(true);
      try {
        await deleteTable(id);
        fetchTables(page, pageSize);
      } catch (error) {
        console.error('Error deleting user:', error);
      }
      setLoading(false);
    }
  };

  const handlePageChange = (event, newPage) => {
    setPage(newPage + 1);
    fetchTables(newPage + 1, pageSize);
  };

  const handlePageSizeChange = (event) => {
    const newPageSize = parseInt(event.target.value, 10);
    setPageSize(newPageSize);
    fetchTables(1, newPageSize);
  };

  const handleSelectAll = (event) => {
    if (event.target.checked) {
      const allRowIds = tables.map((item) => item.id);
      setSelectedRows(allRowIds); // 全选
    } else {
      setSelectedRows([]); // 清空选择
    }
  };
  
  // 单行选择操作
  const handleRowSelect = (id) => {
    setSelectedRows((prev) =>
      prev.includes(id)
        ? prev.filter((rowId) => rowId !== id) // 如果已选中，则取消选择
        : [...prev, id] // 如果未选中，则添加到选中列表
    );
  };
  
    // 批量生成代码
    const handleBatchGenerateCode = async () => {
      if (selectedRows.length === 0) {
        setSnackbarMessage('请选择至少一个表来生成代码');
        return;
      }
  
      try {
        const response = await generateCodeForIds(selectedRows); // 假设 API 接受 ID 列表
        console.log('Generated code for IDs:', selectedRows, response);
        setSnackbarMessage('代码生成成功');
      } catch (error) {
        console.error('Error generating code:', error);
        setSnackbarMessage('代码生成失败，请稍后重试');
      }
    };


  return (
    <Paper >

      <Typography variant="h6" component="div">
        表管理
      </Typography>
      <Form >
        <div style={{ marginBottom: 10, marginTop: 20 }}>
          数据库名称
          <Input
            placeholder="数据库名称"
            value={queryParams.schemaName}
            onChange={(e) => handleQueryParamChange('schemaName', e.target.value)}
            style={{ width: 120, marginRight: 10 }}
          />
          表名称
          <Input
            placeholder="表名称"
            value={queryParams.tableName}
            onChange={(e) => handleQueryParamChange('tableName', e.target.value)}
            style={{ width: 120, marginRight: 10 }}
          />
            <Button
          variant="contained"
          color="primary"
          onClick={handleSearch} // 点击时触发查询
          style={{ marginRight: 10 }}
        >
          查询
        </Button>
        </div>
      </Form>
      <Button color="primary" onClick={handleSyncMetadata}>
        同步数据表
      </Button>
      <Button variant="contained" color="primary" onClick={handleBatchGenerateCode}>
          批量生成代码
        </Button>
      {loading ? (
        <CircularProgress />
      ) : (
        <Table >
          <TableHead>
  <TableRow>
    <TableCell>
      <Checkbox
        checked={selectedRows.length === tables.length && tables.length > 0}
        indeterminate={selectedRows.length > 0 && selectedRows.length < tables.length}
        onChange={handleSelectAll}
      />
    </TableCell>
    {['ID', '表名称', '类名称','库名称', '备注', '操作'].map((header) => (
      <TableCell key={header}>{header}</TableCell>
    ))}
  </TableRow>
</TableHead>
<TableBody>
  {tables.map((item) => (
    <TableRow key={item.id}>
      <TableCell>
        <Checkbox
          checked={selectedRows.includes(item.id)} // 检查当前行是否被选中
          onChange={() => handleRowSelect(item.id)} // 单行选择操作
        />
      </TableCell>
      <TableCell>{item.id}</TableCell>
      <TableCell>{item.tableName}</TableCell>
      <TableCell>{item.className}</TableCell>
      <TableCell>{item.schemaName}</TableCell>
      <TableCell>{item.remark}</TableCell>
      <TableCell>
        <IconButton onClick={() => handleOpenEditDialog(item)}>
          <EditIcon />
        </IconButton>
        <IconButton onClick={() => handleConfirmDeletion(item.id)} color="error">
          <DeleteIcon />
        </IconButton>
        <Button onClick={() => handleReadColumns(item.id,item.tableName)} color="primary">
            表结构
        </Button>
      </TableCell>
    </TableRow>
  ))}
</TableBody>
    
        </Table>
      )}

<div style={{ display: 'flex', justifyContent: 'flex-end', padding: '10px 20px' }}>
    <TablePagination
      component="div"
      count={total}
      page={page - 1}
      onPageChange={handlePageChange}
      rowsPerPage={pageSize}
      onRowsPerPageChange={handlePageSizeChange}
      rowsPerPageOptions={[10, 20, 50]}
    />
  </div>

      <Dialog open={dialogOpen} onClose={handleCloseDialog}>
        <DialogTitle>{editedIndex === -1 ? '创建用户' : '编辑用户'}</DialogTitle>
        <DialogContent>
          <TextField
            value={editedItem.remark}
            onChange={(e) => setEditedItem({ ...editedItem, remark: e.target.value })}
            label="备注"
            fullWidth
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button onClick={handleSaveUser}>保存</Button>
        </DialogActions>
      </Dialog>
      <Snackbar
        open={!!snackbarMessage}
        autoHideDuration={6000}
        onClose={() => setSnackbarMessage('')}
        message={snackbarMessage}
      />
    </Paper>
  );
};

export default TableList;
